package com.pms.framework;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;



public class JSPUtility {

	/**
	 * Returns the boolean parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return boolean value for parameter if non-empty
	 * @throws Exception 
	 * 
	 * @throws BobeException
	 *             with ErrorCode.HTTP_ARGUMENT_NOT_FOUND
	 */
	public static boolean GetBoolean(ServletRequest aRequest, String aName) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)								
			 stringTemp = aRequest.getParameter(aName).trim();
		
		if (stringTemp == null)
			throw new Exception("HTTP_ARGUMENT_NOT_FOUND"+aName);

		return (stringTemp.equalsIgnoreCase("t") || stringTemp
				.equalsIgnoreCase("true")) ? true : false;
	}

	public static boolean GetBooleanMobile(ServletRequest aRequest, String aName) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null)
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_FOUND"+aName);
		if (stringTemp.length()>10)
			throw new Exception("ErrorCode.MOBILE_NO_ERROR"+aName);
		if(stringTemp.charAt(1) == '0')
			throw new Exception("ErrorCode.MOBILE_NO_ERROR"+aName);
		return (stringTemp.equalsIgnoreCase("t") || stringTemp
				.equalsIgnoreCase("true")) ? true : false;
	}
	/**
	 * Returns the boolean parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * @param aDefault
	 *            Value to return if the parameter is not set
	 * 
	 * @return boolean value for parameter if non-empty, default otherwise
	 * 
	 */
	public static boolean GetBoolean(ServletRequest aRequest, String aName,
			boolean aDefault) {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null || (stringTemp.trim().length() == 0))
			return aDefault;

		return (stringTemp.equalsIgnoreCase("t") || stringTemp
				.equalsIgnoreCase("true")) ? true : false;
	}

	/**
	 * Returns the ArrayList parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * @param aDefault
	 *            Value to return if the parameter is not set
	 * 
	 * @return String value for parameter if non-empty, default otherwise
	 * @throws Exception 
	 * 
	 */
	public static ArrayList GetStringArrayList(ServletRequest aRequest,
			String aName) throws Exception {
		try {
			ArrayList arrayList = new ArrayList();
			String[] stringArray = aRequest.getParameterValues(aName);
			if (stringArray != null) {
				for (int i = 0; i < stringArray.length; i++)
					arrayList.add(stringArray[i]);
			}

			return arrayList;
		} catch (NumberFormatException e) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_CANT_PARSE_TO_INT_ARRAY"+aName);
		}
	}

	/**
	 * Returns an array of ints parsed from the HTTPRequest parameter with the
	 * given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return array of integers
	 * @throws Exception 
	 * 
	 */
	public static int[] GetIntArray(ServletRequest aRequest, String aName) throws Exception {

		try {
			int[] intArray = {};

			String[] stringArray = aRequest.getParameterValues(aName);
			if (stringArray != null) {
				intArray = new int[stringArray.length];
				for (int i = 0; i < stringArray.length; i++)
					intArray[i] = Integer.parseInt(stringArray[i]);
			}

			return intArray;
		} catch (NumberFormatException e) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_CANT_PARSE_TO_INT_ARRAY"+aName);
		}
	}

	/**
	 * Returns an array of ints parsed from the HTTPRequest parameter with the
	 * given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return array of integers
	 * @throws Exception 
	 * 
	 */
	public static long[] GetLongArray(ServletRequest aRequest, String aName) throws Exception {

		try {
			long[] longArray = {};

			String[] stringArray = aRequest.getParameterValues(aName);
			if (stringArray != null) {
				longArray = new long[stringArray.length];
				for (int i = 0; i < stringArray.length; i++)
					longArray[i] = Long.parseLong(stringArray[i]);
			}

			return longArray;
		} catch (NumberFormatException e) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_CANT_PARSE_TO_INT_ARRAY"+aName);
		}
	}

	/**
	 * Returns an int parsed from the HTTPRequest parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return array of integers
	 * @throws Exception 
	 * 
	 */
	public static int GetInt(ServletRequest aRequest, String aName) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null)
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_FOUND"+aName);

		try {
			return Integer.parseInt(stringTemp);
		} catch (NumberFormatException ne) {
			throw new Exception("ErrorCode.ATTRIBUTE_NOT_INTEGER"+aName);
		}
	}

	/**
	 * Returns an int parsed from the HTTPRequest parameter with the given name.
	 * In case no parameter was found or an exception occured, the default value
	 * expected is sent back
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return int
	 * 
	 */
	public static int GetInt(ServletRequest aRequest, String aName, int aDefault) {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null)
			return aDefault;

		try {
			return Integer.parseInt(stringTemp);
		} catch (NumberFormatException ne) {
			return aDefault;
		}
	}

	/**
	 * Returns the String parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return String value for parameter if non-empty
	 * @throws Exception 
	 * 
	 * @throws BobeException
	 *             with ErrorCode.HTTP_ARGUMENT_NOT_FOUND
	 */
	public static String GetString(ServletRequest aRequest, String aName) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null)
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_FOUND"+aName);

		return stringTemp;
	}

	/**
	 * Returns the String parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * @param aDefault
	 *            Value to return if the parameter is not set
	 * 
	 * @return String value for parameter if non-empty, default otherwise
	 * 
	 */
	public static String GetString(ServletRequest aRequest, String aName,
			String aDefault) {

		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null)
			return aDefault;

		return stringTemp;
	}

	/**
	 * Returns the boolean for a checkbox parameter.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return boolean value for parameter if non-empty
	 * 
	 * @throws BobeException
	 *             with ErrorCode.HTTP_ARGUMENT_NOT_FOUND
	 */
	public static boolean GetChecked(ServletRequest aRequest, String aName) {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();
		return (stringTemp == null) ? false : true;
	}

	/**
	 * Returns the integer parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return int value for parameter if non-empty
	 * @throws Exception 
	 * 
	 * @throws BobeException
	 *             with ErrorCode.HTTP_ARGUMENT_NOT_FOUND or
	 *             ErrorCode.HTTP_ARGUMENT_NOT_INT
	 */
	public static long GetLong(ServletRequest aRequest, String aName) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null)
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_FOUND"+aName);

		try {
			return Long.parseLong(stringTemp.trim());
		} catch (NumberFormatException e) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_INT"+aName);
		}
	}

	/**
	 * Returns the integer parameter with the given name.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * @param aDefault
	 *            Value to return if the parameter is not set
	 * 
	 * @return int value for parameter if non-empty, default otherwise
	 * @throws Exception 
	 * 
	 * @throws BobeException
	 *             with ErrorCode.HTTP_ARGUMENT_NOT_INT
	 */
	public static long GetLong(ServletRequest aRequest, String aName,
			long aDefault) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if ((stringTemp == null) || (stringTemp.trim().length() == 0))
			return aDefault;

		try {
			return Long.parseLong(stringTemp.trim());
		} catch (NumberFormatException e) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_INT"+aName);
		}
	}

	/**
	 * Returns the double parameter with the given name parsing with a supplied
	 * formatter.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return double value for parameter if non-empty
	 * @throws Exception 
	 * 
	 * @throws BobeException
	 *             with ErrorCode.HTTP_ARGUMENT_NOT_FOUND or
	 *             ErrorCode.HTTP_ARGUMENT_NOT_DOUBLE
	 */
	public static double GetDouble(ServletRequest aRequest, String aName) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null)
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_FOUND"+aName);

		try {
			return Double.parseDouble(stringTemp.trim());
		} catch (Exception e) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_DOUBLE"+aName);
		}
	}

	/**
	 * Returns the double parameter with the given name parsing with a supplied
	 * formatter.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * @param aDefault
	 *            Value to return if the parameter is not set
	 * 
	 * @return double value for parameter if non-empty, default otherwise
	 * @throws Exception 
	 * 
	 * @throws BobeException
	 *             with ErrorCode.HTTP_ARGUMENT_NOT_FOUND or
	 *             ErrorCode.HTTP_ARGUMENT_NOT_DOUBLE
	 */
	public static double GetDouble(ServletRequest aRequest, String aName,
			double aDefault) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if (stringTemp == null || (stringTemp.trim().length() == 0)) {
			return aDefault;
		}

		try {
			return Double.parseDouble(stringTemp.trim());
		} catch (Exception e) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_DOUBLE"+aName);
		}
	}

	/**
	 * Returns the string parameter with the given name only if it contains a
	 * value.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * 
	 * @return String value for parameter if non-empty
	 * @throws Exception 
	 * 
	 * @exception BobeException
	 *                ErrorCode.HTTP_ARGUMENT_NOT_FOUND
	 * 
	 */
	public static String GetNonEmptyString(ServletRequest aRequest, String aName) throws Exception {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if ((stringTemp == null) || (stringTemp.trim().equals(""))) {
			throw new Exception("ErrorCode.HTTP_ARGUMENT_NOT_FOUND"+aName);
		}

		return stringTemp;
	}

	/**
	 * Returns the string parameter with the given name if it contains a value.
	 * 
	 * @param aRequest
	 *            Request to get parameter from
	 * @param aName
	 *            Parameter name
	 * @param aDefault
	 *            Value to return if string is empty
	 * 
	 * @return String value for parameter if non-empty, default otherwise
	 * 
	 */
	public static String GetNonEmptyString(ServletRequest aRequest,
		String aName, String aDefault) {
		String stringTemp=null;
		if(aRequest.getParameter(aName)!=null)
			stringTemp = aRequest.getParameter(aName).trim();

		if ((stringTemp == null) || (stringTemp.trim().equals(""))) {
			return aDefault;
		}

		return stringTemp;
	}

	public static Date getDate(HttpServletRequest request, String string) {
		string = request.getParameter(string);
		StringTokenizer st = new StringTokenizer(string, "/");

		int day = Integer.parseInt(st.nextToken());
		int month = Integer.parseInt(st.nextToken());
		int year = Integer.parseInt(st.nextToken());
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day, 0, 0, 0);
		// Date cDate = new Date(year-1900, month-1, day, 0, 0 ,0);
		// return cDate;
		return cal.getTime();

	}
	
	public static Date getDatediffFormat(HttpServletRequest request, String string) {
		string = request.getParameter(string);
		StringTokenizer st = new StringTokenizer(string, "-");

		int day = Integer.parseInt(st.nextToken());
		int month = Integer.parseInt(st.nextToken());
		int year = Integer.parseInt(st.nextToken());
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day, 0, 0, 0);
		// Date cDate = new Date(year-1900, month-1, day, 0, 0 ,0);
		// return cDate;
		return cal.getTime();

	}

	public static Date getTime(HttpServletRequest request, Date startDate,
			String string) throws Exception {
		string = request.getParameter(string);

		StringTokenizer stringTokenizer = new StringTokenizer(string, ":");
		// StringTokenizer st2 = new StringTokenizer(string," ");
		int hour = Integer.parseInt(stringTokenizer.nextToken());

		stringTokenizer = new StringTokenizer(stringTokenizer.nextToken(), " ");
		int minutes = Integer.parseInt(stringTokenizer.nextToken());

		String amPm = stringTokenizer.nextToken();
		if (amPm.equals(null) || amPm.equalsIgnoreCase("AM")) {
			if(hour==12){
				System.out.println("If hour == 12 Am");
				hour = hour - 12;
				System.out.println("Then add 12 and reult is "+hour);
			}
		} else {
			if(hour!=12)
			hour = hour + 12;
		}

		Calendar calDate = createCalendar(startDate);
		calDate = toStartOfDay(startDate, 0);

		calDate.add(Calendar.HOUR, hour);

		calDate.add(Calendar.MINUTE, minutes);

		Date date = calDate.getTime();
		return date;
	}

	public static Date getTime( Date startDate,
			String string) throws Exception {

		StringTokenizer stringTokenizer = new StringTokenizer(string, ":");
		// StringTokenizer st2 = new StringTokenizer(string," ");
		int hour = Integer.parseInt(stringTokenizer.nextToken());

		stringTokenizer = new StringTokenizer(stringTokenizer.nextToken(), " ");
		int minutes = Integer.parseInt(stringTokenizer.nextToken());

		String amPm = stringTokenizer.nextToken();
		if (amPm.equals(null) || amPm.equalsIgnoreCase("AM")) {
			if(hour==12){
				System.out.println("If hour == 12 Am");
				hour = hour - 12;
				System.out.println("Then add 12 and reult is "+hour);
			}
		} else {
			if(hour!=12)
			hour = hour + 12;
		}

		Calendar calDate = createCalendar(startDate);
		calDate = toStartOfDay(startDate, 0);

		calDate.add(Calendar.HOUR, hour);

		calDate.add(Calendar.MINUTE, minutes);

		Date date = calDate.getTime();
		return date;
	}

	public static String buildMenu(MenuBuild menu) {
		String menuString = "";		
		ArrayList menus = menu.getSubmenu();
		for(int i=0; i < menus.size(); i++) {
			MenuBuild _menu = (MenuBuild)menus.get(i);
			if(_menu!=null)
			{
				menuString = menuString + getSubMenu(_menu, "", i);
			}
		}
		return menuString;
	}
	
	private static String getSubMenu(MenuBuild menu, String currentSequence, int lastId)
    {
    	StringBuffer menuString = new StringBuffer();
    	int sequenceId = lastId + 1;
    	if(currentSequence.equals("")) {
    		currentSequence = "" + sequenceId;
    	} else {
    		currentSequence = currentSequence + "_" + sequenceId;
    	}    	
    	menuString.append("Menu").append(currentSequence)
    			  .append(" = new Array(\"").append(menu.getName())
    			  .append("\",\"").append(menu.getLink()).append("\",\"")
    			  .append(menu.getTarget()).append("\",")
    			  .append(menu.getSubmenu().size()).append(",")
    			  .append(menu.getHeight()).append(",")
    			  .append(menu.getWidth()).append(");\n");

		for(int i=0;i < menu.getSubmenu().size();i++)
	    {
			MenuBuild _menu = (MenuBuild)menu.getSubmenu().get(i);
			menuString.append(getSubMenu(_menu, currentSequence, i));
	    }
	    return menuString.toString();
    }
	
	public static Calendar toStartOfDay(Date startDate,int daysToAddOrSubtract) throws Exception{
		try {
			Calendar aCalendar = createCalendar(startDate);
			
			SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
			String dateString = format.format(aCalendar.getTime());
			dateString = dateString + " 00:00:00";
			format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
			
			Calendar bCalendar = createCalendar(format.parse(dateString));
				
			bCalendar.add(Calendar.DATE, daysToAddOrSubtract);			
			return bCalendar;
		} catch (ParseException e) {
			throw new Exception("Error Parsing Date");
		}
	}
	
	public static Calendar createCalendar(Date startDate){
		
		GregorianCalendar aCalendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Calcutta"));
		aCalendar.setTime(startDate);
		return aCalendar;
	}
	
	
}
